package com.xjtu.duansheli.controller;

import com.xjtu.duansheli.entity.UserInfo;
import com.xjtu.duansheli.json.AjaxResponse;
import com.xjtu.duansheli.service.SendSms;
import com.xjtu.duansheli.service.UserInfoService;
import com.xjtu.duansheli.utils.RedisUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author 刘星宇
 * @version 1.0
 * @date 2020/10/24 19:35
 */

@Slf4j
@RestController
@CrossOrigin
@RequestMapping("/project/user-login")
@Api(value = "登录模块", description = "这是用户登录/登出系统的模块")
public class LoginController {

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private SendSms sendSms;

    @Autowired
    private RedisUtil redisUtil;

    @ApiOperation(value = "发送短信验证码", notes = "用户手机号登陆时发送短信验证码")
    @ApiImplicitParam(name = "phone", value = "用户手机号", required = true, paramType = "query", dataType = "String")
    @RequestMapping(value = "/send", method = RequestMethod.GET)
    public AjaxResponse send(@RequestParam(value = "phone") String phone) {
        UserInfo userInfo = userInfoService.getUserByPhone(phone);
        if (userInfo == null) {
            return AjaxResponse.error(400, "手机号未注册");
        }
        String code = String.valueOf(redisUtil.get(phone));
        if (redisUtil.hasKey(phone)) {
            return AjaxResponse.error(phone + ":" + code + "已存在，还未过期！");
        }
        code = UUID.randomUUID().toString().substring(0, 4);
        HashMap<String, Object> param = new HashMap<>();
        param.put("code", code);
        boolean isSend = sendSms.send(phone, "SMS_204127841", param);
        if (isSend) {
            redisUtil.set(phone, code, 60);
            return AjaxResponse.success(phone + ":" + code + "发送成功！");
        } else {
            return AjaxResponse.error("发送失败！");
        }
    }

    @ApiOperation(value = "用户登录", notes = "用户登录的接口")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "phone", value = "用户手机号", required = true, paramType = "form", dataType = "String"),
            @ApiImplicitParam(name = "codeUser", value = "用户输入验证码", required = true, paramType = "form", dataType = "String")
    })
    @RequestMapping(value = "/logIn", method = RequestMethod.POST)
    public AjaxResponse login(@RequestParam(value = "phone") String phone,
                              @RequestParam(value = "codeUser") String codeUser,
                              HttpServletRequest request,
                              HttpServletResponse resp) {
        String code = String.valueOf(redisUtil.get(phone));
        System.out.println(code);
        if (!codeUser.equalsIgnoreCase(code)) {
            return AjaxResponse.error(400, "输入验证码为空或者错误！");
        }
        UserInfo userInfo = userInfoService.getUserByPhone(phone);
        request.getSession().setAttribute("loginUser", userInfo);
        Cookie nameCookie = new Cookie("phone", phone);
        resp.addCookie(nameCookie);
        nameCookie.setMaxAge(60 * 60 * 24);
        return AjaxResponse.success("登陆成功！");
    }

    @ApiOperation(value = "用户登出", notes = "用户登出的接口")
    @RequestMapping(value = "/logOut", method = RequestMethod.GET)
    public AjaxResponse logout(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        try {
            UserInfo user = (UserInfo) session.getAttribute("loginUser");
            if (user == null) {
                return AjaxResponse.error("登陆状态已经失效！");
            }
        } catch (Exception e) {
            log.info(e.getMessage());
        }
        session.removeAttribute("loginUser");
        return AjaxResponse.success("登出成功！");
    }

}
